<template>
	<el-card shadow="hover" class="quick-config-card" :class="{ collapsed: isCollapsed }">
		<template #header>
			<div class="card-header">
				<el-icon style="display: inline; vertical-align: middle"> <ele-Setting /> </el-icon>
				<span>快捷展示</span>
				<div class="header-actions">
					<el-button type="primary" size="small" icon="ele-Edit" @click="openConfigDrawer" style="margin-right: 10px"> 配置 </el-button>
					<el-button type="info" size="small" :icon="isCollapsed ? 'ele-Expand' : 'ele-Fold'" @click="toggleCollapse" :title="isCollapsed ? '展开' : '折叠'">
						{{ isCollapsed ? '展开' : '折叠' }}
					</el-button>
				</div>
			</div>
		</template>

		<!-- 快捷展示区域 -->
		<div class="quick-display" v-if="selectedConfigs.length > 0 && !isCollapsed">
			<!-- 区域统计展示 -->
			<div class="display-section" v-if="selectedAreas.length > 0">
				<h4>区域统计 ({{ selectedAreas.length }})</h4>
				<div class="display-grid">
					<div v-for="area in selectedAreas" :key="area.value || 'null'" class="display-item area-item">
						<div class="item-header">
							<el-icon><ele-Location /></el-icon>
							<span class="item-title">{{ area.label }}</span>
						</div>
						<div class="item-stats" v-if="areaStats[area.value || 0]">
							<div class="stat-row">
								<span class="stat-label">开工率:</span>
								<span class="stat-value">{{ areaStats[area.value || 0].startRate }}%</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">完工率:</span>
								<span class="stat-value">{{ areaStats[area.value || 0].endRate }}%</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">开工数:</span>
								<span class="stat-value">{{ areaStats[area.value || 0].actualStartTotal }}/{{ areaStats[area.value || 0].planStartTotal }}</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">完工数:</span>
								<span class="stat-value">{{ areaStats[area.value || 0].actualEndTotal }}/{{ areaStats[area.value || 0].planEndTotal }}</span>
							</div>
						</div>
						<div class="item-loading" v-else>
							<el-skeleton :rows="4" animated />
						</div>
					</div>
				</div>
			</div>

			<!-- 分类统计展示 -->
			<div class="display-section" v-if="selectedCategories.length > 0">
				<h4>分类统计 ({{ selectedCategories.length }})</h4>
				<div class="display-grid">
					<div v-for="category in selectedCategories" :key="category.value || 'null'" class="display-item category-item">
						<div class="item-header">
							<el-icon><ele-Files /></el-icon>
							<span class="item-title">{{ category.label }}</span>
						</div>
						<div class="item-stats" v-if="categoryStats[category.value || 0]">
							<div class="stat-row">
								<span class="stat-label">开工率:</span>
								<span class="stat-value">{{ categoryStats[category.value || 0].startRate }}%</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">完工率:</span>
								<span class="stat-value">{{ categoryStats[category.value || 0].endRate }}%</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">开工数:</span>
								<span class="stat-value">{{ categoryStats[category.value || 0].actualStartTotal }}/{{ categoryStats[category.value || 0].planStartTotal }}</span>
							</div>
							<div class="stat-row">
								<span class="stat-label">完工数:</span>
								<span class="stat-value">{{ categoryStats[category.value || 0].actualEndTotal }}/{{ categoryStats[category.value || 0].planEndTotal }}</span>
							</div>
						</div>
						<div class="item-loading" v-else>
							<el-skeleton :rows="4" animated />
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 折叠状态显示 -->
		<div class="collapsed-state" v-if="isCollapsed">
			<div class="collapsed-summary">
				<el-icon><ele-InfoFilled /></el-icon>
				<span v-if="selectedConfigs.length > 0"> 已配置 {{ selectedAreas.length }} 个区域，{{ selectedCategories.length }} 个分类 </span>
				<span v-else> 暂无快捷展示配置 </span>
				<el-button type="primary" size="small" @click="toggleCollapse" style="margin-left: 10px">
					{{ selectedConfigs.length > 0 ? '展开查看' : '展开配置' }}
				</el-button>
			</div>
		</div>

		<!-- 空状态 -->
		<div class="empty-state" v-if="selectedConfigs.length === 0 && !isCollapsed">
			<el-empty description="暂无快捷展示配置" :image-size="60">
				<el-button type="primary" @click="openConfigDrawer">立即配置</el-button>
			</el-empty>
		</div>

		<!-- 配置抽屉 -->
		<el-drawer title="快捷展示配置" v-model="configDrawer" :size="600" destroy-on-close :before-close="beforeClose">
			<div class="config-drawer-content">
				<!-- 区域配置 -->
				<div class="config-section-drawer">
					<h4>选择区域 ({{ selectedAreas.length }})</h4>
					<div class="config-options">
						<div v-for="area in availableAreas" :key="area.value || `area-${area.label}`" class="config-option" :class="{ active: isAreaSelected(area.value) }" @click="toggleArea(area)">
							<el-icon><ele-Location /></el-icon>
							<span>{{ area.label }}</span>
							<el-icon v-if="isAreaSelected(area.value)" class="check-icon">
								<ele-Check />
							</el-icon>
						</div>
					</div>
				</div>

				<!-- 分类配置 -->
				<div class="config-section-drawer">
					<h4>选择分类 ({{ selectedCategories.length }})</h4>
					<div class="config-options">
						<div
							v-for="category in availableCategories"
							:key="category.value || `category-${category.label}`"
							class="config-option"
							:class="{ active: isCategorySelected(category.value) }"
							@click="toggleCategory(category)"
						>
							<el-icon><ele-Files /></el-icon>
							<span>{{ category.label }}</span>
							<el-icon v-if="isCategorySelected(category.value)" class="check-icon">
								<ele-Check />
							</el-icon>
						</div>
					</div>
				</div>
			</div>

			<template #footer>
				<div style="margin: 0 20px 20px 0">
					<el-button @click="beforeClose">取消</el-button>
					<el-button type="primary" @click="saveConfig">保存配置</el-button>
				</div>
			</template>
		</el-drawer>
	</el-card>
</template>

<script lang="ts" setup name="QuickConfig">
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Local } from '/@/utils/storage';
import { usePlanViewApi } from '/@/api/plans/planView';

interface ConfigItem {
	value: number | null;
	label: string;
}

interface StatsData {
	actualStartTotal: number;
	planStartTotal: number;
	actualEndTotal: number;
	planEndTotal: number;
	startRate: number;
	endRate: number;
}

interface Props {
	availableAreas: ConfigItem[];
	availableCategories: ConfigItem[];
	queryParams: {
		workTime: string;
		className: number | null;
		workAreaId: number | null;
		keyword: string;
		advancedField: string;
	};
}

const props = defineProps<Props>();

const planViewApi = usePlanViewApi();
const configDrawer = ref<boolean>(false);
const selectedAreas = ref<ConfigItem[]>([]);
const selectedCategories = ref<ConfigItem[]>([]);
const areaStats = ref<Record<number, StatsData>>({});
const categoryStats = ref<Record<number, StatsData>>({});
const isCollapsed = ref<boolean>(true); // 新增：控制快捷展示区域是否折叠

// 计算属性
const selectedConfigs = computed(() => [...selectedAreas.value, ...selectedCategories.value]);

// 检查区域是否已选择
const isAreaSelected = (value: number | null) => {
	return selectedAreas.value.some((area) => area.value === value);
};

// 检查分类是否已选择
const isCategorySelected = (value: number | null) => {
	return selectedCategories.value.some((category) => category.value === value);
};

// 切换区域选择
const toggleArea = (area: ConfigItem) => {
	const index = selectedAreas.value.findIndex((item) => item.value === area.value);
	if (index > -1) {
		selectedAreas.value.splice(index, 1);
		// 清除对应的统计数据
		if (area.value) {
			delete areaStats.value[area.value];
		}
	} else {
		selectedAreas.value.push(area);
		// 加载对应的统计数据
		if (area.value) {
			loadAreaStats(area.value);
		}
	}
};

// 切换分类选择
const toggleCategory = (category: ConfigItem) => {
	const index = selectedCategories.value.findIndex((item) => item.value === category.value);
	if (index > -1) {
		selectedCategories.value.splice(index, 1);
		// 清除对应的统计数据
		if (category.value) {
			delete categoryStats.value[category.value];
		}
	} else {
		selectedCategories.value.push(category);
		// 加载对应的统计数据
		if (category.value) {
			loadCategoryStats(category.value);
		}
	}
};

// 加载区域统计数据
const loadAreaStats = async (areaId: number) => {
	try {
		const params = {
			workTime: props.queryParams.workTime,
			workAreaId: areaId,
			className: null,
			keyword: props.queryParams.keyword,
		};

		const res = await planViewApi.getPlanCounts(params);
		if (res && res.data && res.data.result) {
			const result = res.data.result;
			areaStats.value[areaId] = {
				actualStartTotal: result.actualStartTotal ?? 0,
				planStartTotal: result.planStartTotal ?? 0,
				actualEndTotal: result.actualEndTotal ?? 0,
				planEndTotal: result.planEndTotal ?? 0,
				startRate: result.startRate ?? 0,
				endRate: result.endRate ?? 0,
			};
		}
	} catch (error) {
		console.error('加载区域统计数据失败:', error);
		ElMessage.error('加载区域统计数据失败');
	}
};

// 加载分类统计数据
const loadCategoryStats = async (categoryId: number) => {
	try {
		const params = {
			workTime: props.queryParams.workTime,
			className: categoryId,
			workAreaId: null,
			keyword: props.queryParams.keyword,
		};

		const res = await planViewApi.getPlanCounts(params);
		if (res && res.data && res.data.result) {
			const result = res.data.result;
			categoryStats.value[categoryId] = {
				actualStartTotal: result.actualStartTotal ?? 0,
				planStartTotal: result.planStartTotal ?? 0,
				actualEndTotal: result.actualEndTotal ?? 0,
				planEndTotal: result.planEndTotal ?? 0,
				startRate: result.startRate ?? 0,
				endRate: result.endRate ?? 0,
			};
		}
	} catch (error) {
		console.error('加载分类统计数据失败:', error);
		ElMessage.error('加载分类统计数据失败');
	}
};

// 刷新所有统计数据
const refreshAllStats = async () => {
	// 刷新区域统计
	for (const area of selectedAreas.value) {
		if (area.value) {
			await loadAreaStats(area.value);
		}
	}

	// 刷新分类统计
	for (const category of selectedCategories.value) {
		if (category.value) {
			await loadCategoryStats(category.value);
		}
	}
};

// 打开配置抽屉
const openConfigDrawer = () => {
	configDrawer.value = true;
};

// 保存配置
const saveConfig = () => {
	const config = {
		areas: selectedAreas.value,
		categories: selectedCategories.value,
		timestamp: Date.now(),
	};
	Local.set('planViewQuickConfig', config);
	ElMessage.success('快捷展示配置保存成功');
	configDrawer.value = false;
};

// 取消配置
const beforeClose = () => {
	// 恢复之前的配置
	loadSavedConfig();
	configDrawer.value = false;
};

// 加载保存的配置
const loadSavedConfig = () => {
	try {
		const savedConfig = Local.get('planViewQuickConfig');
		if (savedConfig && savedConfig.areas && savedConfig.categories) {
			selectedAreas.value = savedConfig.areas;
			selectedCategories.value = savedConfig.categories;
		}
	} catch (error) {
		console.error('加载快捷配置失败:', error);
	}
};

// 切换折叠状态
const toggleCollapse = () => {
	isCollapsed.value = !isCollapsed.value;
	// 保存折叠状态到本地存储
	Local.set('planViewQuickConfigCollapsed', isCollapsed.value);
};

// 监听查询参数变化，刷新统计数据
watch(
	() => props.queryParams,
	() => {
		refreshAllStats();
	},
	{ deep: true }
);

// 监听可用数据变化，更新已选择的项目
watch(
	() => props.availableAreas,
	(newAreas) => {
		// 过滤掉不存在的区域
		selectedAreas.value = selectedAreas.value.filter((selected) => newAreas.some((available) => available.value === selected.value));
	},
	{ deep: true }
);

watch(
	() => props.availableCategories,
	(newCategories) => {
		// 过滤掉不存在的分类
		selectedCategories.value = selectedCategories.value.filter((selected) => newCategories.some((available) => available.value === selected.value));
	},
	{ deep: true }
);

// 加载折叠状态
const loadCollapsedState = () => {
	try {
		const savedCollapsed = Local.get('planViewQuickConfigCollapsed');
		// 默认折叠，除非用户之前明确设置为展开
		isCollapsed.value = savedCollapsed !== false;
	} catch (error) {
		console.error('加载折叠状态失败:', error);
		// 默认折叠
		isCollapsed.value = true;
	}
};

// 初始化时加载配置和统计数据
onMounted(() => {
	loadSavedConfig();
	loadCollapsedState();
	refreshAllStats();
});
</script>

<style scoped lang="scss">
.quick-config-card {
	background: var(--el-bg-color);
	border-radius: 4px;
	border: 1px solid var(--el-border-color-light);
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	margin-bottom: 10px;

	.card-header {
		display: flex;
		align-items: center;
		font-size: 16px;
		font-weight: 600;
		color: white;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		border-radius: 8px 8px 0 0;
		padding: 15px 20px;
		margin: -20px -20px 20px -20px;

		.header-actions {
			margin-left: auto;
		}
	}

	// 折叠状态下的样式优化
	&.collapsed {
		margin-bottom: 3px; // 进一步减少底部间距，从10px减少到3px

		.card-header {
			padding: 8px 15px; // 减少内边距，从15px 20px减少到8px 15px
			margin: -20px -20px 0px -20px; // 移除底部间距
			border-radius: 4px; // 折叠时四角都圆角
		}

		// 完全隐藏卡片body，减少不必要的空间
		:deep(.el-card__body) {
			display: none; // 完全隐藏body，而不是设置padding为0
		}

		// 整体高度更紧凑
		min-height: auto;
	}
}

.quick-display {
	.display-section {
		margin-bottom: 25px;

		h4 {
			font-size: 16px;
			font-weight: 600;
			color: var(--el-text-color-primary);
			margin-bottom: 15px;
			padding-bottom: 8px;
			border-bottom: 2px solid var(--el-color-primary);
		}

		.display-grid {
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
			gap: 15px;
		}

		.display-item {
			background: white;
			border: 1px solid var(--el-border-color-light);
			border-radius: 4px;
			padding: 15px;
			transition: all 0.3s ease;

			&:hover {
				box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
				transform: translateY(-2px);
			}

			&.area-item {
				border-left: 4px solid #667eea;
			}

			&.category-item {
				border-left: 4px solid #f093fb;
			}

			.item-header {
				display: flex;
				align-items: center;
				gap: 8px;
				margin-bottom: 12px;
				padding-bottom: 8px;
				border-bottom: 1px solid var(--el-border-color-lighter);

				.item-title {
					font-size: 14px;
					font-weight: 600;
					color: var(--el-text-color-primary);
				}
			}

			.item-stats {
				.stat-row {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 8px;

					&:last-child {
						margin-bottom: 0;
					}

					.stat-label {
						font-size: 13px;
						color: var(--el-text-color-regular);
					}

					.stat-value {
						font-size: 13px;
						font-weight: 600;
						color: var(--el-text-color-primary);

						&:has(.stat-value:contains('%')) {
							color: var(--el-color-success);
						}
					}
				}
			}

			.item-loading {
				padding: 10px 0;
			}
		}
	}
}

.collapsed-state {
	padding: 20px;
	background-color: var(--el-fill-color-light);
	border-radius: 4px;
	margin-top: 20px;

	.collapsed-summary {
		display: flex;
		align-items: center;
		gap: 10px;
		font-size: 14px;
		color: var(--el-text-color-secondary);

		.el-icon {
			font-size: 18px;
			color: var(--el-color-info);
		}

		span {
			flex: 1;
		}
	}
}

.empty-state {
	padding: 40px 0;
	text-align: center;
}

.config-drawer-content {
	padding: 0 20px;
}

.config-section-drawer {
	margin-bottom: 30px;

	h4 {
		font-size: 16px;
		font-weight: 600;
		color: var(--el-text-color-primary);
		margin-bottom: 15px;
		padding-bottom: 8px;
		border-bottom: 2px solid var(--el-color-primary);
	}

	.config-options {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
		gap: 10px;
		max-height: 300px;
		overflow-y: auto;
		padding: 10px;
		border: 1px solid var(--el-border-color-light);
		border-radius: 4px;
		background: var(--el-fill-color-lighter);
	}

	.config-option {
		display: flex;
		align-items: center;
		gap: 8px;
		padding: 12px;
		border-radius: 4px;
		cursor: pointer;
		transition: all 0.3s ease;
		background: white;
		border: 1px solid var(--el-border-color-light);
		position: relative;

		&:hover {
			border-color: var(--el-color-primary);
			box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
		}

		&.active {
			background: var(--el-color-primary);
			color: white;
			border-color: var(--el-color-primary);

			.check-icon {
				position: absolute;
				right: 8px;
				top: 50%;
				transform: translateY(-50%);
				font-size: 16px;
			}
		}

		span {
			flex: 1;
			font-size: 14px;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}
	}
}

// 响应式设计
@media (max-width: 768px) {
	.quick-config-card {
		margin-bottom: 15px;

		.card-header {
			padding: 12px 15px;
			margin: -15px -15px 15px -15px;
			font-size: 14px;

			.header-actions {
				margin-left: auto;
			}
		}

		// 移动端折叠状态优化
		&.collapsed {
			margin-bottom: 5px;

			.card-header {
				padding: 8px 12px;
				margin: -15px -15px 0px -15px;
			}
		}
	}
}

.quick-display {
	.display-section {
		.display-grid {
			grid-template-columns: 1fr;
			gap: 12px;
		}

		.display-item {
			padding: 12px;
		}
	}
}

.collapsed-state {
	padding: 15px;

	.collapsed-summary {
		flex-direction: column;
		align-items: flex-start;
		gap: 8px;

		.el-icon {
			font-size: 16px;
		}

		span {
			text-align: center;
			width: 100%;
		}
	}
}

.config-section-drawer {
	.config-options {
		grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
		gap: 8px;
	}

	.config-option {
		padding: 10px;
		font-size: 13px;
	}
}
</style>
